<template>
  <div class="paper-detail">
    <div
      class="flex justify-between border-gray-400 border-b-1 h-[100px] items-center px-5"
    >
      <div class="count-down" v-if="!route.query.show">
        剩余时间：{{ formatTime(countdownSeconds) }}
      </div>
      <div class="count-down" v-else></div>
      <h5 class="title" v-if="paper && paper.name">
        {{ paper.Exam.name }}-{{ paper.name }}
      </h5>
      <n-button
        class="submit"
        @click="handleSubmit"
        type="primary"
        v-if="!route.query.show"
      >
        提交试卷
      </n-button>
      <n-button class="submit" @click="handleBackFolder" type="warning" v-else>
        返回目录
      </n-button>
    </div>
    <n-layout has-sider class="h-[80vh] flex">
      <n-layout-sider
        bordered
        collapse-mode="width"
        :collapsed-width="10"
        :width="300"
        :collapsed="collapsed"
        show-trigger
        @collapse="collapsed = true"
        @expand="collapsed = false"
      >
        <div class="text-center">答题卡</div>
        <div v-if="radioArr.length">
          <div class="mx-4">单项选择题</div>
          <div class="flex flex-wrap p-3 !pt-1">
            <n-button
              class="w-[40px] h-[40px] ml-2 mt-2 flex justify-center items-center"
              :type="
                item.isError
                  ? 'error'
                  : item.yourAnswer || item.yourAnswerList.length
                    ? 'success'
                    : activeIndex === index
                      ? 'primary'
                      : 'default'
              "
              v-for="(item, index) in radioArr"
              :key="item.id"
              @click="activeIndex = index"
            >
              {{ index + 1 }}
            </n-button>
          </div>
        </div>
        <div v-if="mulArr.length">
          <div class="mx-4">多项选择题</div>
          <div class="flex flex-wrap p-3 !pt-1">
            <n-button
              class="w-[40px] h-[40px] ml-2 mt-2 flex justify-center items-center"
              :type="
                item.isError
                  ? 'error'
                  : item.yourAnswer || item.yourAnswerList.length
                    ? 'success'
                    : activeIndex === index + radioArr.length
                      ? 'primary'
                      : 'default'
              "
              v-for="(item, index) in mulArr"
              :key="item.id"
              @click="activeIndex = index + radioArr.length"
            >
              {{ index + radioArr.length + 1 }}
            </n-button>
          </div>
        </div>
        <div v-if="panduanArr.length">
          <div class="mx-4">判断题</div>
          <div class="flex flex-wrap p-3 !pt-1">
            <n-button
              class="w-[40px] h-[40px] ml-2 mt-2 flex justify-center items-center"
              :type="
                item.isError
                  ? 'error'
                  : item.yourAnswer || item.yourAnswerList.length
                    ? 'success'
                    : activeIndex === index + radioArr.length + mulArr.length
                      ? 'primary'
                      : 'default'
              "
              v-for="(item, index) in panduanArr"
              :key="item.id"
              @click="activeIndex = index + radioArr.length + mulArr.length"
            >
              {{ index + radioArr.length + mulArr.length + 1 }}
            </n-button>
          </div>
        </div>
      </n-layout-sider>
      <n-layout :class="{ 'w-[95vw]': collapsed, 'w-[80vw]': !collapsed }">
        <div
          v-loading="loading"
          v-if="questions.length"
          class="flex flex-col justify-between w-full"
          :style="{ fontSize: curFontSize + 'px' }"
        >
          <div class="question-area p-3">
            <div
              class="panel w-full h-[50px] border-b-[2px] flex justify-between"
            >
              <p class="question-title" v-if="+curQuestion.type === 1">
                单项选择题（每小题备选答案中，只有一个符合题意的正确答案。多选、错选、不选均不得分。请使用计算机鼠标在计算机答题界面上点击试题答案备选项前的按钮“○”作答。）
              </p>
              <p class="question-title" v-if="+curQuestion.type === 2">
                多项选择题（每小题备选答案中，有两个或两个以上符合题意的正确答案。多选、少选、错选、不选均不得分。请使用计算机鼠标在计算机答题界面上点击试题答案备选项前的按钮“□”作答。）
              </p>
              <p class="question-title" v-if="+curQuestion.type === 4">
                判断题（请使用计算机鼠标在计算机答题界面上点击试题答案备选项前的按钮“○”作答。）
              </p>
              <div>
                <span
                  @click="curFontSize++"
                  style="font-size: 12px; margin-left: 3px; cursor: pointer"
                >
                  + 放大
                </span>
                <span
                  @click="curFontSize--"
                  style="font-size: 12px; margin-left: 3px; cursor: pointer"
                  >- 缩小</span
                >
                <span
                  @click="curFontSize = 14"
                  style="font-size: 12px; margin-left: 3px; cursor: pointer"
                  >重置</span
                >
              </div>
            </div>
            <p v-html="curQuestion.name"></p>
            <n-radio-group
              v-if="+curQuestion.type === 1 || +curQuestion.type === 4"
              v-model:value="curQuestion.yourAnswer"
              name="radiogroup"
            >
              <n-space vertical>
                <n-radio
                  v-for="(item, index) in curQuestion.options"
                  :key="curQuestion.id + index"
                  :value="`${String.fromCharCode(65 + index)}`"
                >
                  <p :style="{ fontSize: curFontSize + 'px' }">
                    {{ `${String.fromCharCode(65 + index)}. ${item.trim()}` }}
                  </p>
                </n-radio>
              </n-space>
            </n-radio-group>

            <n-checkbox-group
              v-model:value="curQuestion.yourAnswerList"
              v-if="+curQuestion.type === 2"
            >
              <n-grid :y-gap="8" :cols="1">
                <n-gi
                  v-for="(v, i) in curQuestion.options"
                  :key="curQuestion.id + i"
                >
                  <n-checkbox :value="`${String.fromCharCode(65 + i)}`">
                    <p :style="{ fontSize: curFontSize + 'px' }">
                      {{ `${String.fromCharCode(65 + i)}. ${v.trim()}` }}
                    </p>
                  </n-checkbox>
                </n-gi>
              </n-grid>
            </n-checkbox-group>

            <n-input
              v-if="+curQuestion.type === 3"
              v-model:value="curQuestion.yourAnswer"
              type="textarea"
              placeholder="请输入内容"
            />

            <div class="flex">
              <n-button
                @click="activeIndex--"
                v-if="activeIndex > 0"
                style="margin-right: 7px"
                >{{ '上一题' }}</n-button
              >
              <n-button
                @click="activeIndex++"
                v-if="activeIndex < questions.length - 1"
                >{{ '下一题' }}</n-button
              >
              <n-button
                @click="showAnswerArea = !showAnswerArea"
                style="margin-left: 7px"
                >{{ '解析' }}</n-button
              >
            </div>
          </div>
          <div class="answer-area p-2 m-4 border" v-if="showAnswerArea">
            <!-- <n-button @click="showAnswerArea = !showAnswerArea">{{
              showAnswerArea ? '隐藏答案' : '显示答案'
            }}</n-button> -->
            <div>你的答案：{{ yourAnswers[activeIndex] }}</div>
            <div>
              正确答案：<span style="color: #38c860">{{
                curQuestion.answer
              }}</span>
            </div>
            <div>
              <div v-html="curQuestion.analysis"></div>
            </div>
          </div>
        </div>
      </n-layout>
    </n-layout>
  </div>
</template>

<script setup lang="ts">
import { getQuestionByPage } from '@/api/question'
import { getPaperById } from '@/api/paper'
import type { QuestionRowInfo } from '@/types/question'
import { useMessage, useDialog } from 'naive-ui'
import { createExamHistory, getExamHistoryByPage } from '@/api/examHistory'
import useUserStore from '@/stores/modules/user'
import { getItem, setItem } from '@/utils/storage'
import { userLoading } from '@/hooks/useLoading'
import { getErrorQuestionByPage } from '@/api/errorQuestion'
import { getQuestionFavByPage } from '@/api/questionFav'
const router = useRouter()
const route = useRoute()
const collapsed = ref(false)
const message = useMessage()
const dialog = useDialog()
const userStore = useUserStore()

const activeIndex = ref(0)
const curFontSize = ref(14)

const questions = ref<QuestionRowInfo[]>([])

const showAnswerArea = ref(false)

const curQuestion = computed(() => {
  return questions.value[activeIndex.value]
})

const { loading, openLoading, closeLoading } = userLoading()

const radioArr = computed(() => {
  const info = questions.value.filter((item) => {
    return +item.type === 1
  })

  console.log('info', info)

  return info
})

const mulArr = computed(() => {
  return questions.value.filter((item) => {
    return +item.type === 2
  })
})

const panduanArr = computed(() => {
  return questions.value.filter((item) => {
    return +item.type === 4
  })
})

const splitArr = ref([])

const loadQuestions = () => {
  // 根据type类型获取不同题目，1-试卷题目，2-试卷错题，3-收藏题目
  if ('' + route.query.type === '2') {
    // 获取试卷错题
    getErrorQuestionByPage({
      paperId: route.query.paperId as string,
      page: 1,
      pageSize: 999
    })
      .then((res) => {
        const d = res.data.items.map((v) => v.Question)
        renderData(d)
      })
      .catch(console.error)
  } else if ('' + route.query.type === '3') {
    // 获取收藏题目
    getQuestionFavByPage({
      paperId: route.query.paperId as string,
      page: 1,
      pageSize: 999
    }).then((res) => {
      const d = res.data.items.map((v) => v.Question)
      renderData(d)
    })
  } else {
    getQuestionByPage({
      paperId: route.query.paperId as string,
      page: 1,
      pageSize: 999
    })
      .then((res) => {
        renderData(res.data.items)
      })
      .catch(console.error)
  }
}

const renderData = (items: any) => {
  questions.value = items.map((item: any) => {
    return {
      ...item,
      options: (item.options as string).split('||'),
      yourAnswer: '',
      yourAnswerList: []
    }
  })

  // 计算分割数组
  // for (let i = 0; i < res.data.items.length; i++) {
  //   const a = res.data.items[i]
  // }

  // // 获取当前记录
  const infos1 = getItem(route.query.paperId + 'answer')
  // console.log(infos1)
  if (infos1 && infos1.length) {
    questions.value = items.map((item: any, index: any) => {
      return {
        ...item,
        options: (item.options as string).split('||'),
        yourAnswer: infos1[index].yourAnswer,
        yourAnswerList: infos1[index].yourAnswerList
      }
    })
  }

  if (route.query.show) {
    loadExamHistory()
  }
}

const paper = ref()

const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
    .toString()
    .padStart(2, '0')
  const minutes = Math.floor((seconds % 3600) / 60)
    .toString()
    .padStart(2, '0')
  const secs = (seconds % 60).toString().padStart(2, '0')
  return `${hours}:${minutes}:${secs}`
}
const loadPaperById = () => {
  getPaperById(route.query.paperId as string)
    .then((res) => {
      paper.value = res.data.paper
      const times = getItem(paper.value.id + 'time')
      const currentIndex = getItem(paper.value.id + 'currentIndex')
      if (currentIndex) {
        activeIndex.value = currentIndex
      }
      if (times) {
        countdownSeconds.value = times
      } else {
        countdownSeconds.value = paper.value.time * 60
      }

      timer.value = setInterval(() => {
        if (countdownSeconds.value > 0) {
          countdownSeconds.value--
          if (countdownSeconds.value === 0) {
            // 倒计时结束，自动提交
            clearInterval(timer.value)
            handleSubmit()
          }
        }
      }, 1000)
    })
    .catch(console.error)
}

const timer = ref()
const countdownSeconds = ref(0)
onMounted(() => {
  window.addEventListener('beforeunload', handleRefresh)
  showAnswerArea.value = route.query.show ? true : false
  // const paperId = route.query.paperId
  loadPaperById()
  loadQuestions()
  // 如果展示，需要获取当前用户最新一次的记录
  // 显示倒计时
})

onUnmounted(() => {
  clearInterval(timer.value)
})

onBeforeUnmount(() => {
  // console.log('xxx111');
  window.removeEventListener('beforeunload', handleRefresh)
})

const handleRefresh = (e: any) => {
  console.log(e, 'reflesh')
  // route.query.isNew = false

  setItem(paper.value.id + 'time', countdownSeconds.value - 1)

  const answerInfos = questions.value.map((v) => ({
    yourAnswer: v.yourAnswer,
    yourAnswerList: v.yourAnswerList
  }))

  setItem(paper.value.id + 'answer', answerInfos)
  setItem(paper.value.id + 'currentIndex', activeIndex.value)
  // 保存作答记录
}

const yourAnswers = ref<string[]>([])
const loadExamHistory = async () => {
  if (!userStore.userInfo) {
    await userStore.getUserInfo()
  }
  openLoading()
  getExamHistoryByPage({
    page: 1,
    pageSize: 1,
    userId: userStore.userInfo?.id,
    paperId: route.query.paperId as string,
    type: route.query.type as string
  })
    .then((res) => {
      // 获取你的answer
      if (res.data.items.length) {
        // 最新一次的
        const cur = res.data.items[res.data.items.length - 1]
        yourAnswers.value = cur.answers.split(',')
        // console.log(yourAnswers.value, 'answruuuu')

        questions.value.forEach((v, index) => {
          v.yourAnswer =
            yourAnswers.value[index] === '无' ? '' : yourAnswers.value[index]
          v.yourAnswerList =
            yourAnswers.value[index] === '无'
              ? []
              : yourAnswers.value[index].split('')
          // v.isRight=your
          if (v.yourAnswer) {
            v.isError = v.yourAnswer !== v.answer
          }
          if (v.yourAnswerList.length) {
            v.isError = v.yourAnswerList.join('') !== v.answer
          }
        })
        // questions.value = [...questions.value]
      }
    })
    .finally(() => {
      closeLoading()
    })
}

const handleSubmit = () => {
  const no = questions.value.some(
    (v) => v.yourAnswer === '' && v.yourAnswerList.length === 0
  )
  // if(no){
  //   return message.w
  // }
  dialog.warning({
    title: '温馨提示',
    content: no ? '还有题目未作答，确定提交吗？' : '你确定提交试卷吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      // message.success('确定')
      const answers = questions.value
        .map((v) => {
          if (v.yourAnswerList.length > 0) {
            return v.yourAnswerList.join('')
          } else if (v.yourAnswer) {
            return v.yourAnswer
          } else {
            return '无'
          }
        })
        .join(',')

      createExamHistory({
        paperId: route.query.paperId as string,
        answers: answers,
        userId: userStore.userInfo?.id as string,
        type: route.query.type as string
      })
        .then(() => {
          message.success('提交成功')
          router.push({
            name: 'paperResult',
            query: {
              paperId: route.query.paperId as string,
              userId: userStore.userInfo?.id,
              examId: route.query.examId as string,
              type: route.query.type as string
            }
          })
        })
        .catch((err) => {
          console.log(err)
          message.error('提交失败')
        })
    },
    onNegativeClick: () => {}
  })
}

const handleBackFolder = () => {
  router.push({
    name: 'chapterList',
    query: {
      examId: route.query.examId as string
    }
  })
}
</script>

<style scoped lang="scss">
.paper-detail {
  .answer-area {
    line-height: 2;
  }
}
</style>
